package cn.nfwx.tv.controller;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.reflect.TypeToken;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.List;

import cn.nfwx.tv.activity.AdvertiseActivity;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.down.utils.LogUtils;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.AdvertiseManager;
import cn.nfwx.tv.model.Advertise;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.util.GlideUtil;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static cn.nfwx.tv.activity.AdvertiseActivity.TYPE_BEFORE;
import static cn.nfwx.tv.activity.AdvertiseActivity.TYPE_JIAOBIAO;
import static cn.nfwx.tv.activity.AdvertiseActivity.TYPE_PAUSE;
import static cn.nfwx.tv.activity.AdvertiseActivity.TYPE_START;

/**
 * Created by dell on 2018/4/17.
 */

public class AdvertiseController {

    static AdvertiseController instance;

    static final String TAG = AdvertiseController.class.getSimpleName();

    public static AdvertiseController getInstance() {
        if (instance == null) {
            synchronized (AdvertiseController.class) {
                if (instance == null) {
                    instance = new AdvertiseController();
                }
            }
        }
        return instance;
    }

    private final String SVGA_CACHE_KEY = "nfwxsvga";

    private static final String key_preferen_str = "key_preferen_str"; // 返回数据

    private static final String key_preferen_start_str = "key_preferen_start_str"; // 启动广告图链接路径

    private static final String key_preferen_start_local = "key_preferen_start_local"; // 启动广告图的本地路径

    private static final String key_preferen_jiaobiao_str = "Key_preferen_jiaobiao_str"; // 启动角标广告

    private static final String key_preferen_jiaobiao_local = "key_preferen_jiaobiao_local"; // 角标本地

    private static final String key_preferen_start_interval = "key_preferen_start_interval"; // 启动图的时长

    private static final String key_preferen_jiaobiao_interval = "key_preferen_jiaobiao_interval"; // 角标的

    private String requestAdvertiseCommand = "";

    public void loadAdvertiseList(final Context context) {
        if (!TextUtils.isEmpty(requestAdvertiseCommand)) {
            CustomOkHttpClient.cancleAll(requestAdvertiseCommand);
        }
        AdvertiseManager.requestIjkAdvertiseList(context, new ResponseWithFailListener<String>() {
            @Override
            public void onResponse(String requestTag, String response) {
                try {
                    Result<List<Advertise>> result = JSON.parseObject(response, new TypeReference<Result<List<Advertise>>>() {
                    }.getType());
                    if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_str, response);
                        for (Advertise advertise : result.getData()) {
                            String fileName = "advertise.jpg";
                            int type = -1;
                            String str;
                            boolean needLoad = false;
                            if (advertise.getType() == TYPE_START) {
                                String url = advertise.getUrl();
                                if (!TextUtils.isEmpty(url)) {
                                    fileName = "advertise_start.jpg";
                                    type = TYPE_START;
                                    str = getStartAdvertiseStr(context);
                                    if (!advertise.getUrl().equals(str)) {
                                        SharePrefUtil.saveAdvertiseLocal(context, key_preferen_start_local, "");
                                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_start_str, advertise.getUrl());
                                        needLoad = true;
                                    }
                                } else {
                                    SharePrefUtil.saveAdvertiseLocal(context, key_preferen_start_local, "");
                                    SharePrefUtil.saveAdvertiseStr(context, key_preferen_start_str, "");
                                }
                            }
                            if (advertise.getType() == TYPE_JIAOBIAO) {
                                int i = advertise.getInterval();
                                if (i > 0) {
                                    if (advertise.getApplycid().contains("all")) {
                                        SharePrefUtil.saveAdvertiseInt(context, key_preferen_jiaobiao_interval, i);
                                    } else {
                                        SharePrefUtil.saveAdvertiseInt(context, key_preferen_jiaobiao_interval + "_" + advertise.getApplycid(), i);
                                    }
                                }
                                if (advertise.getApplycid().contains("all")) {
                                    if (!TextUtils.isEmpty(advertise.getUrl())) {
                                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_str, advertise.getUrl());
                                    } else {
                                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_str, "");
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(advertise.getUrl())) {
                                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_str + "_" + advertise.getApplycid(), advertise.getUrl());
                                    } else {
                                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_str + "_" + advertise.getApplycid(), "");
                                    }
                                }
                            }
                            if (needLoad) {
                                DownloadCallback downloadCallback = new DownloadCallback(context, fileName, type);
                                final Handler handler = new Handler(Looper.getMainLooper(), downloadCallback);
                                GlideUtil.downloadImage(context, advertise.getUrl(), new ValueCallback<File>() {
                                    @Override
                                    public void onReceiveValue(File value) {
                                        Message message = handler.obtainMessage(0, value.getAbsolutePath());
                                        handler.sendMessage(message);
                                    }
                                });
                            }
                        }
                    }
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }

            @Override
            public void onError(String requestTag, Throwable t) {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFail(String requestTag, String response) {

            }
        });
    }

    /**
     * 获取启动图图片
     *
     * @param context
     * @return
     */
    public String getStartAdvertise(Context context) {
        return SharePrefUtil.getAdvertiseLocal(context, key_preferen_start_local);
    }


    /**
     * 获取广告内容
     *
     * @param context
     * @return
     */
    public String getStartAdvertiseStr(Context context) {
        return SharePrefUtil.getAdvertiseStr(context, key_preferen_start_str);
    }

    /**
     * 广告内容
     *
     * @param context
     * @return
     */
    public String getAdvertiseStr(Context context) {
        return SharePrefUtil.getAdvertiseStr(context, key_preferen_str);
    }

    /**
     * 间隔时长
     *
     * @param context
     * @return
     */
    public int getInterval(Context context, int type, String cid) {
        if (type == TYPE_JIAOBIAO) {
            int interval = SharePrefUtil.getAdvertiseInt(context, key_preferen_jiaobiao_interval + "_" + cid);
            if (interval == -1) {
                interval = SharePrefUtil.getAdvertiseInt(context, key_preferen_jiaobiao_interval);
            }
            if (interval > 0) {
                return interval * 1000;
            }
        }
        return 60 * 1000;
    }

    /**
     * 显示时长
     *
     * @param context
     * @param type
     * @return
     */
    public int getDurTime(Context context, int type) {
        String data = getAdvertiseStr(context);
        if (TextUtils.isEmpty(data)) {
            return 60 * 1000;
        }
        try {
            Result<List<Advertise>> result = JSON.parseObject(data, new TypeReference<Result<List<Advertise>>>() {
            }.getType());
            for (Advertise advertise : result.getData()) {
                if (advertise.getType() == type) {
                    return advertise.getDuration() * 1000;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 60 * 1000;
    }

    public static final int IMG_TYPE_NO = -1;
    public static final int IMG_TYPE_SVGA = 1;
    public static final int IMG_TYPE_PNG = 2;

    private static class SvgaParseCompletion implements SVGAParser.ParseCompletion {

        WeakReference<SVGAImageView> weakReference;

        public SvgaParseCompletion(SVGAImageView imageView) {
            weakReference = new WeakReference<>(imageView);
        }

        @Override
        public void onComplete(SVGAVideoEntity videoItem) {
            SVGAImageView imageView = weakReference.get();
            if (imageView == null) {
                return;
            }
            SVGADrawable drawable = new SVGADrawable(videoItem);
            imageView.setImageDrawable(drawable);
            imageView.setClickable(true);
            imageView.startAnimation();
        }

        @Override
        public void onError() {

        }
    }

    /**
     * 加在角标文件
     */
    public synchronized int loadJiaoBiao(final Context context, final SVGAImageView imageView, String gid) {
        if (context == null || TextUtils.isEmpty(gid)) {
            return IMG_TYPE_NO;
        }
        String data = getAdvertiseStr(context);
        if (!TextUtils.isEmpty(data)) {
            try {
                String url = SharePrefUtil.getAdvertiseStr(context, key_preferen_jiaobiao_str + "_" + gid);
                if (TextUtils.isEmpty(url)) {
                    gid = "all";
                    url = SharePrefUtil.getAdvertiseStr(context, key_preferen_jiaobiao_str);
                } else {
                    Result<List<Advertise>> result = JSON.parseObject(data, new TypeReference<Result<List<Advertise>>>() {
                    }.getType());
                    boolean gidclear = true;
                    for (Advertise advertise : result.getData()) {
                        if (advertise.getType() == TYPE_JIAOBIAO) {
                            if (advertise.getApplycid().equals(gid)) {
                                if (TextUtils.isEmpty(advertise.getUrl())) {
                                    gidclear = true;
                                } else {
                                    gidclear = false;
                                }
                                break;
                            }
                        }
                    }
                    if (gidclear) {
                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_str + "_" + gid, "");
                        String fileName = SharePrefUtil.getAdvertiseStr(context, key_preferen_jiaobiao_local + "_" + gid);
                        File file = context.getFileStreamPath(fileName);
                        if (file.exists()) {
                            file.delete();
                        }
                        SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_local + "_" + gid, "");
                    }
                }
                if (!TextUtils.isEmpty(url)) {
                    if (url.contains(".svga")) {
                        imageView.setImageDrawable(null);
                        imageView.stopAnimation(true);
                        SVGAParser parser = new SVGAParser(context);
                        String fileName;
                        if (gid.equals("all")) {
                            fileName = SharePrefUtil.getAdvertiseStr(context, key_preferen_jiaobiao_local);
                        } else {
                            fileName = SharePrefUtil.getAdvertiseStr(context, key_preferen_jiaobiao_local + "_" + gid);
                        }
                        if (TextUtils.isEmpty(fileName)) {
                            try {
                                resetDownloader(context, parser, gid);
                                parser.parse(new URL(url), new SvgaParseCompletion(imageView));
                            } catch (Exception ignored) {

                            }
                        } else {
                            File file = context.getFileStreamPath(fileName);
                            if (file.exists()) {
                                FileInputStream fileInputStream = context.openFileInput(fileName);
                                if (fileInputStream != null) {
                                    parser.parse(fileInputStream, SVGA_CACHE_KEY, new SvgaParseCompletion(imageView));
                                }
                            } else {
                                if (gid.equals("all")) {
                                    SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_local, "");
                                } else {
                                    SharePrefUtil.saveAdvertiseStr(context, key_preferen_jiaobiao_local + "_" + gid, "");
                                }
                                loadJiaoBiao(context, imageView, gid);
                            }
                        }
                        return IMG_TYPE_SVGA;
                    } else {
                        imageView.stopAnimation(true);
                        imageView.setImageDrawable(null);
                        imageView.setClickable(true);
                        GlideUtil.loadImage(context, url, imageView);
                        return IMG_TYPE_PNG;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return IMG_TYPE_NO;
        }
        return IMG_TYPE_NO;
    }

    /**
     * 加载启动图片
     */
    public boolean loadStar(Context context, ImageView imageView) {
        if (context == null) {
            return false;
        }
        String url = AdvertiseController.getInstance().getStartAdvertiseStr(context);
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        String start = AdvertiseController.getInstance().getStartAdvertise(context);
        if (!TextUtils.isEmpty(start)) {
            FileInputStream fileInputStream = null;
            Bitmap bitmap;
            try {
                fileInputStream = context.openFileInput(start);
                if (fileInputStream != null) {
                    bitmap = BitmapFactory.decodeStream(fileInputStream);
                    imageView.setImageBitmap(bitmap);
                    return true;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 加载暂停图片
     */
    public void loadPause(Context context, ImageView imageView, String gid) {
        Log.i(TAG, "loadPause");
        if (context == null) {
            return;
        }
        loadStrImage(context, imageView, TYPE_PAUSE, gid);
    }

    /**
     * 获取广告返回信息图片
     */
    private void loadStrImage(Context context, ImageView imageView, int type, String gid) {
        Log.i(TAG, "GlideUtil loadImage loadStrImage");
        String data;
        imageView.setImageDrawable(null);
        imageView.setVisibility(View.GONE);
        switch (type) {
            case TYPE_START:
                data = AdvertiseController.getInstance().getStartAdvertiseStr(context);
                if (!TextUtils.isEmpty(data)) {
                    try {
                        Advertise advertise = JSON.parseObject(data, new TypeToken<Advertise>() {
                        }.getType());
                        GlideUtil.loadImage(context, advertise.getUrl(), imageView, imageView.getWidth(), imageView.getHeight());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case TYPE_BEFORE:
            case TYPE_PAUSE:
                data = getAdvertiseStr(context);
                if (!TextUtils.isEmpty(data)) {
                    try {
                        Result<List<Advertise>> result = JSON.parseObject(data, new TypeReference<Result<List<Advertise>>>() {
                        }.getType());
                        String url = null;
                        for (Advertise advertise : result.getData()) {
                            if (advertise.getType() == type) {
                                if (advertise.getApplycid().equals(gid)) {
                                    url = advertise.getUrl();
                                    break;
                                } else if (advertise.getApplycid().equals("all")) {
                                    url = advertise.getUrl();
                                }
                            }
                        }
                        if (!TextUtils.isEmpty(url)) {
                            GlideUtil.loadImage(context, url, imageView);
                            imageView.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }

    }


    /**
     * 跳转至启动广告的网页
     *
     * @param context
     */
    public boolean gotoStartWeb(Context context) {
        String startWeb = getForward(context, TYPE_START, "all");
        if (!TextUtils.isEmpty(startWeb)) {
            AdvertiseActivity.startActivity(context, startWeb, TYPE_START);
            return true;
        }
        return false;
    }

    /**
     * @param context
     */
    public void gotoPauseWeb(Context context, String gid) {
        String pauseWeb = getForward(context, TYPE_PAUSE, gid);
        if (!TextUtils.isEmpty(pauseWeb)) {
            AdvertiseActivity.startActivity(context, pauseWeb, TYPE_PAUSE);
        }
    }

    /**
     * 跳转角标的链接
     *
     * @param context
     */
    public void gotoJiaoBiaoWeb(Context context, String gid) {
        String jiaobiaoWeb = getForward(context, TYPE_JIAOBIAO, gid);
        if (!TextUtils.isEmpty(jiaobiaoWeb)) {
            AdvertiseActivity.startActivity(context, jiaobiaoWeb, TYPE_JIAOBIAO);
        }
    }

    /**
     * 获取跳转链接
     *
     * @param context
     * @param type
     * @return
     */
    public String getForward(Context context, int type, String gid) {
        String data = getAdvertiseStr(context);
        if (TextUtils.isEmpty(data) || TextUtils.isEmpty(gid)) {
            return "";
        }
        try {
            Result<List<Advertise>> result = JSON.parseObject(data, new TypeReference<Result<List<Advertise>>>() {
            }.getType());
            String forward = "";
            for (Advertise advertise : result.getData()) {
                if (advertise.getType() == type) {
                    if (advertise.getApplycid().equals(gid)) {
                        forward = advertise.getForward();
                        break;
                    } else if (advertise.getApplycid().equals("all")) {
                        forward = advertise.getForward();
                    }
                }
            }
            return forward;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 回调
     */
    private static class DownloadCallback implements Handler.Callback {

        private WeakReference<Context> weakReference;
        private String fileName;
        private int mType;

        public DownloadCallback(Context context, String fileName, int type) {
            weakReference = new WeakReference<Context>(context);
            this.fileName = fileName;
            mType = type;
        }

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (fileName == null) {
                        break;
                    }
                    Log.i(TAG, "DownloadCallback start");
                    FileOutputStream fileOutputStream = null;
                    FileInputStream fileInputStream = null;
                    try {
                        Context context = weakReference.get();
                        if (context == null) {
                            break;
                        }
                        String filePath = (String) msg.obj;
                        LogUtil.e(TAG, filePath);
                        fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
                        File file = new File(filePath);
                        if (file.exists()) {
                            fileInputStream = new FileInputStream(file);
                            int length = 0;
                            byte[] data = new byte[1024];
                            while ((length = fileInputStream.read(data)) != -1) {
                                fileOutputStream.write(data, 0, length);
                            }
                        }
                        Log.i(TAG, "DownloadCallback end");
                        if (mType == TYPE_START) {
                            SharePrefUtil.saveAdvertiseLocal(context, key_preferen_start_local, fileName);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (fileOutputStream != null) {
                                fileOutputStream.close();
                            }
                            if (fileInputStream != null) {
                                fileInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
            return false;
        }
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param context
     * @param parser
     * @param gid
     */
    private void resetDownloader(final Context context, SVGAParser parser, final String gid) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String svgaFileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                        OkHttpClient client = CustomOkHttpClient.getOkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            ResponseBody responseBody = response.body();
                            if (responseBody != null) {
                                FileOutputStream fileOutputStream = null;
                                FileInputStream fileInputStream = null;
                                try {
                                    File file = context.getFileStreamPath(svgaFileName);
                                    if (file.exists()) {
                                        file.delete();
                                    }
                                    fileOutputStream = context.openFileOutput(svgaFileName, Context.MODE_PRIVATE);
                                    int length = 0;
                                    byte[] data = new byte[1024];
                                    while ((length = responseBody.byteStream().read(data)) != -1) {
                                        fileOutputStream.write(data, 0, length);
                                    }
                                    if (gid.equals("all")) {
                                        SharePrefUtil.saveAdvertiseLocal(context, key_preferen_jiaobiao_local, svgaFileName);
                                    } else {
                                        SharePrefUtil.saveAdvertiseLocal(context, key_preferen_jiaobiao_local + "_" + gid, svgaFileName);
                                    }
                                    fileInputStream = context.openFileInput(svgaFileName);
                                    complete.invoke(fileInputStream);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        if (fileOutputStream != null) {
                                            fileOutputStream.close();
                                        }
                                        if (fileInputStream != null) {
                                            fileInputStream.close();
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }
}
